<template>
  <div class="policy-items-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableData">
        <template #headerLeft>
          <a-space>
            <p>共计 {{ total }} 条</p>
            <a-dropdown :popup-max-height="false">
              <a-button v-if="$authPass('policy-template.create')" type="primary">添加策略 <icon-down /></a-button>
              <template #content>
                <a-doption @click="openAddDialog('BUDGET_POLICY')">分时调整预算</a-doption>
                <a-doption @click="openAddDialog('BIDDING_POLICY')">分时调整竞价</a-doption>
                <a-doption @click="openAddDialog('SWITCH_POLICY')">分时启停</a-doption>
                <a-doption @click="openAddDialog('TARGETING_POLICY')">分时调广告位</a-doption>
              </template>
            </a-dropdown>
          </a-space>
        </template>
        <template #tableBody>
          <a-table class="table-two-line" ref="tableRef" row-key="id" :loading="tableLoading" :bordered="false" :data="tableList" :scroll="{ y: '100%' }" size="mini" :pagination="false">
            <template #columns>
              <a-table-column title="序号" :width="45">
                <template #cell="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
              </a-table-column>
              <a-table-column title="策略名称" data-index="policyName" />
              <a-table-column title="策略类型">
                <template #cell="{ record }">
                  <p>{{ PolicyType[record.policyType] }}</p>
                </template>
              </a-table-column>
              <a-table-column title="有效期">
                <template #cell="{ record }">
                  <p v-if="!record.effectiveEndDate && !record.effectiveStartDate">一直有效</p>
                  <p v-else>{{ record.effectiveStartDate }}~{{ record.effectiveEndDate }}</p>
                </template>
              </a-table-column>
              <a-table-column title="策略明细" :width="340">
                <template #cell="{ record }">
                  <PolicyRuleDetail :policyType="record.policyType" :detail="record" :ruleList="record.policyTemplateRuleDOS" />
                </template>
              </a-table-column>
              <a-table-column title="适用站点">
                <template #cell="{ record }">
                  <p>{{ getMarketplace(record.applicableMarketplace) }}</p>
                </template>
              </a-table-column>
              <a-table-column title="是否共享">
                <template #cell="{ record }">
                  <p>{{ record.isShare === 1 ? '是' : '否' }}</p>
                </template>
              </a-table-column>
              <a-table-column title="应用明细">
                <template #cell="{ record }">
                  <div class="flex-c">
                    <p class="highlight cursor" @click="openPolicyItemDialog(record)" style="margin-right: 10px">{{ record.policyTargetingNum }}</p>
                    <a-button type="text" v-if="$authPass('policy-targeting.batch.save')" @click="openAddPolicyItem(record)">添加</a-button>
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="创建时间" :width="140">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtCreate) }}</p>
                </template>
              </a-table-column>
              <a-table-column title="创建人" data-index="createUserName" />
              <a-table-column title="更新人" data-index="updateUserName" />
              <a-table-column title="操作">
                <template #cell="{ record }">
                  <a-space>
                    <a-button type="text" v-if="$authPass('policy-template.create')" @click="openAddDialog(record.policyType, record)">编辑</a-button>
                    <a-dropdown>
                      <icon-more class="table-btn-more" />
                      <template #content>
                        <!-- <a-doption>复制</a-doption> -->
                        <a-doption v-if="$authPass('policy-template.delete')" @click="deleteItem(record)">删除</a-doption>
                        <!-- <a-doption @click.stop="openLog(record)">日志</a-doption> -->
                      </template>
                    </a-dropdown>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 日志列表 -->
  <PolicyTemplateLog v-if="showLogDialog" :userList="userList" :isShow="showLogDialog" @closed="showLogDialog = false" />
  <!-- 添加和编辑分时策略模板 -->
  <AddAndEditPolicyTemplate v-if="showAddDialog" :policyType="policyType" :currentData="currentData" :markedtList="markedtList" :isShow="showAddDialog" @closed="showAddDialog = false" @success="getTableData" />
  <!-- 分时策略模板明细 -->
  <PolicyTempItemDetail v-if="showPolicyItemDetail" :shopList="shopList" :currentData="currentData" :isShow="showPolicyItemDetail" @closed="showPolicyItemDetail = false" />
  <!-- 添加分时策略明细 -->
  <AddPolicyItem v-if="showAddPolicyItem" :shopList="shopList" :currentData="currentData" :isShow="showAddPolicyItem" @closed="showAddPolicyItem = false" @success="getTableData" />
</template>

<script lang="ts" setup>
  import { ref, watchEffect, onMounted } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { getPolicyTemplateList, deletePolicyTemplateList } from '@/api/advert'
  import TableWrap from '@/components/TableWrap.vue'
  import PolicyTemplateLog from './components/policyTemplateLog.vue'
  import PolicyTempItemDetail from './components/policyTempItemDetail.vue'
  import AddPolicyItem from './components/addPolicyItem.vue'
  import AddAndEditPolicyTemplate from './components/addAndEditPolicyTemplate.vue'
  import PolicyRuleDetail from './components/policyRuleDetail.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { PolicyType } from '../types'
  import { marketPlaceList } from '@/utils/globalData'
  import { FilterTableItem } from '@/types/components'
  onMounted(() => {
    getTableData()
  })
  const props = defineProps({
    markedtList: {
      type: Array,
      default: () => [],
    },
    userList: {
      type: Array,
      default: () => [],
    },
    shopList: {
      type: Array,
      default: () => [],
    },
  })
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplaceIds',
      label: '站点',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'policyTypes',
      label: '分时策略类型',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        {
          label: '分时调整预算',
          value: 'BUDGET_POLICY',
        },
        {
          label: '分时调整竞价',
          value: 'BIDDING_POLICY',
        },
        {
          label: '分时启停',
          value: 'SWITCH_POLICY',
        },
        {
          label: '分时调整广告位',
          value: 'TARGETING_POLICY',
        },
      ],
    },
    {
      key: 'policyName',
      label: '策略名称',
      value: ref(),
      type: 'input_search',
      width: 150,
    },
    {
      key: 'createUserName',
      label: '创建人',
      value: ref(),
      type: 'select',
      width: 120,
      optionField: {
        label: 'label',
        value: 'label',
      },
    },
    {
      key: 'updateUserName',
      label: '更新人',
      value: ref(),
      type: 'select',
      width: 120,
      optionField: {
        label: 'label',
        value: 'label',
      },
    },
    {
      key: 'createDate',
      label: '创建日期',
      value: ref(),
      type: 'date_range',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        placeholder: ['创建开始日期', '创建结束日期'],
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  let searchVal = ref({
    pageSize: 20,
    pageNum: 1,
  })
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([{}, {}])
  const showLogDialog = ref(false)
  const showPolicyItemDetail = ref(false)
  const showAddDialog = ref(false)
  const showAddPolicyItem = ref(false)
  const currentData = ref({})
  const policyType = ref()
  const filterData = ref<any>({})

  // 通过条件查询用户列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    filterData.value.marketplaceIds = filterData.value.marketplaceIds ? filterData.value.marketplaceIds.split(',') : undefined
    filterData.value.policyTypes = filterData.value.policyTypes ? filterData.value.policyTypes.split(',') : undefined
    filterData.value.gmtCreateStart = filterData.value.createDate?.[0]
    filterData.value.gmtCreateEnd = filterData.value.createDate?.[1]
    delete filterData.value.createDate
    getTableData()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableData()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableData()
  }
  // 显示站点名称
  function getMarketplace(marketplaces: string) {
    let arr = marketplaces?.split(',')
    let names = arr?.map((val: string) => marketPlaceList[val]?.code)
    return names?.join(',')
  }
  // 获取列表数据
  async function getTableData() {
    let params = {
      pageNum: searchVal.value.pageNum,
      pageSize: searchVal.value.pageSize,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await getPolicyTemplateList(params)
    tableLoading.value = false
    tableList.value = res?.data?.data || []
    total.value = res?.data?.total || 0
  }
  //打开分时策略明细
  function openPolicyItemDialog(row: any) {
    currentData.value = row
    showPolicyItemDetail.value = true
  }
  //打开添加分时策略明细
  function openAddPolicyItem(row: any) {
    currentData.value = row
    showAddPolicyItem.value = true
  }
  // 删除
  function deleteItem(row: any) {
    Modal.warning({
      title: '删除',
      content: '确认是否删除策略？一旦删除不可恢复，请谨慎操作！',
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      hideCancel: false,
      onOk: async () => {
        let res: any = await deletePolicyTemplateList({ policyId: row.id })
        if (res) {
          Message.success('删除成功')
          getTableData()
        }
      },
    })
  }
  // 查看日志
  // function openLog(row: any) {
  //   currentData.value = row
  //   showLogDialog.value = true
  // }
  // 添加或者编辑分时策略模板
  function openAddDialog(type: string, row?: any) {
    policyType.value = type
    currentData.value = row || {}
    showAddDialog.value = true
  }
  watchEffect(() => {
    if (props.markedtList?.length) {
      filterItem.value[0].optionItems = props.markedtList
    }
    if (props.userList?.length) {
      filterItem.value[3].optionItems = props.userList
      filterItem.value[4].optionItems = props.userList
    }
  })
</script>
<style lang="less" scoped>
  .policy-items-wrap {
    height: calc(100vh - @menuAndTabHeight) !important;
  }
</style>
